package com.xmindguoguo.boot.util.spring;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * 关于springmvc 的一些工具类
 * 
 * @ClassName SpringMvcUtil
 * @author <a href="892042158@qq.com" target="_blank">于国帅</a>
 * @date 2019年1月9日 上午2:30:49
 *
 */
public class SpringMvcUtil {
    public static Set<String> getHandlerHandlerMappingAllUrl(WebApplicationContext wac) {
        Set<String> urlSet = new HashSet<>();// 存储所有url集合
        Map<String, HandlerMapping> requestMappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(wac, HandlerMapping.class, true,
                false);
        for (HandlerMapping handlerMapping : requestMappings.values()) {
            if (handlerMapping instanceof RequestMappingHandlerMapping) {
                // 内部很深的水啊
                RequestMappingHandlerMapping rmhm = (RequestMappingHandlerMapping) handlerMapping;
                Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
                for (RequestMappingInfo rmi : handlerMethods.keySet()) {
                    PatternsRequestCondition prc = rmi.getPatternsCondition();
                    // 获取到了所有的url 因为不知道接下来干什么，所以暂时忽略掉
                    Set<String> patterns = prc.getPatterns();
                    for (String uStr : patterns) {
                        if (StringUtils.isNotBlank(uStr)) { // 如果url为空 则不加入
                            urlSet.add(uStr);
                        }
                    }
                }
            }
        }
        return urlSet;
    }

    public static WebApplicationContext WebApplicationContext(HttpServletRequest request) {
        return (WebApplicationContext) request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);// 获取上下文对象
    }

}
